//201902104030_何琛选
package cn.edu.sdjzu.xg.bysj.service;

import cn.edu.sdjzu.xg.bysj.dao.CommonDao;
import cn.edu.sdjzu.xg.bysj.dao.DegreeDao;
import cn.edu.sdjzu.xg.bysj.domain.Degree;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;
import util.bysjException;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public final class DegreeService {
    private static DegreeDao degreeDao = DegreeDao.getInstance();
    private static DegreeService degreeService =new DegreeService();
    private DegreeService(){}

    public static DegreeService getInstance(){
        return degreeService;
    }

    public Collection<Degree> findAll(
            List<Condition> conditionList_json_str, Pagination pagination)
            throws SQLException {
        //获得链接以便完成可能的事务操作
        Connection connection = JdbcHelper.getConn();
        Collection<Degree> degrees = degreeDao.findAll(
                connection,conditionList_json_str,pagination);
        JdbcHelper.close(connection);
        return degrees;
    }

    public Degree find(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Degree degree = degreeDao.find(id,connection);
        JdbcHelper.close(connection);
        return degree;
    }

    public boolean update(Degree degree) throws SQLException {
        boolean result = false;
        Connection connection = JdbcHelper.getConn();
        result = degreeDao.update(degree,connection);
        JdbcHelper.close(connection);
        return result;
    }

    public boolean add(Degree degree) throws SQLException {
        boolean result = false;
        Connection connection = JdbcHelper.getConn();
        result = degreeDao.add(degree,connection);
        JdbcHelper.close(connection);
        return result;
    }

    public boolean delete(Integer id) throws SQLException, bysjException {
        boolean result = false;
        Connection connection = JdbcHelper.getConn();
        result = this.delete(this.find(id));
        JdbcHelper.close(connection);
        return result;
    }

    public boolean delete(Degree degree) throws SQLException, bysjException {
        boolean result = false;
        Connection connection = JdbcHelper.getConn();
        //获得所有下一级单位（DepartmentController）
        int countTeacherOfDepartment = CommonDao.getInstance().
                countWhereForeignKey(connection,"teacher","degree_id",degree.getId());
        //若没有二级单位，则能够删除
        if(countTeacherOfDepartment==0){
            result = degreeDao.delete(degree,connection);
        }else {
            throw new bysjException(degree.getDescription()+"有下属系，不能删除");
        }
        JdbcHelper.close(connection);
        return result;
    }

}

